package cn.itlaobing.web.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.itlaobing.entity.Student;
import cn.itlaobing.service.StudentService;

@Controller
@RequestMapping("/students")
public class StudentController {
	
	@Autowired
	private StudentService studentService;
	
	/**
	 * 共有的请求
	 * */
	@ModelAttribute
	public void preparedDate(@PathVariable(required=false)Integer id,Model model) {
		if(id==null) {
			model.addAttribute("student",new Student());
		}else {
			model.addAttribute("student",studentService.findById(id));
		}
	}
	@GetMapping
	public String show(Model model){
		List<Student> list=studentService.findAll();
		model.addAttribute("students",list);
		return "students/show";
	}
	
	@GetMapping("/create")
	public String _new(Model model) {
		return "students/create";
	}
	
	@PostMapping("/create")
	public String create(@ModelAttribute("student") @Valid Student student,BindingResult bindingResult,Model model) {
		if(bindingResult.hasErrors()) {
			model.addAttribute("student",student);
			return "students/create";
		}
		studentService.save(student);
		return("redirect:/students");
	}
	
	@GetMapping("/{id}/update")
	public String update() {
		return "students/update";
	}
	
	@PostMapping("/{id}/update")
	public String update(@ModelAttribute("student") @Valid Student student,BindingResult bindingResult) {
		studentService.update(student);
		return("redirect:/students");
	}
	
	@GetMapping("/{id}/delete")
	@ResponseBody
	public String delete(@PathVariable Integer id) {
		studentService.delete(id);
		return "OK";
	}
	
	
}
